package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-04
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper,AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 报警过滤
     */
    @Override
    public void alertFilter() {
        //判断规则是否为空
        long count = count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if(count <= 0){
            return;
        }
        //查询所有设备上报的最新的数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if(CollUtil.isEmpty(values)){
            return;
        }
        //整理数据，装入一个集合中
        List<DeviceData> deviceDataList = new ArrayList<>();
        values.forEach(v-> deviceDataList.addAll(JSONUtil.toList(v.toString(), DeviceData.class)));

        //处理报警数据，逐条处理
        deviceDataList.forEach(d-> alertFilter(d));

    }

    /**
     * 处理报警数据
     * @param deviceData
     */
    private void alertFilter(DeviceData deviceData) {

        //上报的时间不能超过1分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if(between > 60){
            return;
        }

        //查询所有的规则数据  条件 iotId、functionId（属性）、产品的key、状态1
        List<AlertRule> alertRules = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getIotId, "-1")
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1));

        //查询对应的规则数据
        List<AlertRule> iotIdalertRules = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1));
        //集合合并
        //alertRules.addAll(iotIdalertRules);
        Collection<AlertRule> allAlertRules = CollUtil.addAll(alertRules, iotIdalertRules);
        if(CollUtil.isEmpty(allAlertRules)){
            return;
        }

        allAlertRules.forEach(alertRule -> deviceDataAlarmHandler(alertRule, deviceData));

    }

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.managerRole}")
    private String managerRole;

    /**
     * 根据规则过滤上报的数据
     * @param alertRule
     * @param deviceData
     */
    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        //判断上报的数据的上报时间是否在规则的生效时段内  00:02:00~20:59:59
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        //上报时间
        LocalTime time = deviceData.getAlarmTime().toLocalTime();
        if(time.isBefore(startTime) || time.isAfter(endTime)){
            return;
        }

        String aggCountKey = CacheConstants.IOT_ALERT_COUNT+deviceData.getIotId()+":"+alertRule.getFunctionId()+":"+alertRule.getId();

        //校验上报的数据是否达到了规则内的阈值
        Double dataValue = Double.valueOf(deviceData.getDataValue());  //60
        Double value = alertRule.getValue();  //65
        //判断两个值的大小，（x,y） x等于y返回0  x>y 返回1  x<y 返回-1
        int compare = NumberUtil.compare(dataValue, value);
        if((alertRule.getOperator().equals(">=") && compare >= 0) || (alertRule.getOperator().equals("<") && compare < 0)){
            System.out.println("产生了异常数据");
        }else {
            System.out.println("正常数据");
            redisTemplate.delete(aggCountKey);
            return;
        }
        //判断是否在沉默周期内
        //key，要保证唯一性  iot+functionid+规则id
        String silentKey = CacheConstants.IOT_ALERT_SILENT+deviceData.getIotId()+":"+alertRule.getFunctionId()+":"+alertRule.getId();
        String silentData = redisTemplate.opsForValue().get(silentKey);
        if(StringUtils.isNotEmpty(silentData)){
            return;
        }
        //持续周期

        String aggCountData = redisTemplate.opsForValue().get(aggCountKey);
        //判断累加值是否存在，不存在则设置为1，存在则累加1
        Integer count = StringUtils.isEmpty(aggCountData)? 1 : Integer.parseInt(aggCountData) + 1;
        if(ObjectUtil.notEqual(count, alertRule.getDuration())){
            redisTemplate.opsForValue().set(aggCountKey, count+"");
            return;
        }
        //出现了异常数据了  创建一个沉默周期，删除累加次数，新增报警数据
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        redisTemplate.delete(aggCountKey);

        List<Long> userIds = new ArrayList<>();

        //判断是否是老人的异常数据
        if(alertRule.getAlertDataType().equals(0)){
            if(deviceData.getLocationType().equals(0)){
                //随身设备  iotId-->老人-->nursing_elder
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());

            }else if(deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals(2)){
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }else {
            //设备异常数据,要通过角色名称来获取对应的人员-->行政
            userIds =  sysUserRoleMapper.selectIdsByRoleName(deviceMaintainerRole);
        }

        List<Long> managerIds  =  sysUserRoleMapper.selectIdsByRoleName(managerRole);
        //合并后去重
        Collection<Long> ids = CollUtil.addAll(userIds, managerIds);
        //去重
        ids = CollUtil.distinct(ids);

        //保存报警数据
        List<AlertData> alertDataList = insertAlertData(deviceData, alertRule, ids);

        //websocket发送消息
        wesocketNotify(alertDataList.get(0),alertRule,ids);

    }

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * websocket推送消息
     * @param alertData
     * @param alertRule
     * @param ids
     */
    private void wesocketNotify(AlertData alertData, AlertRule alertRule, Collection<Long> ids) {

        //属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setAccessLocation(alertData.getRemark());
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        //向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo,ids);
    }

    @Autowired
    private IAlertDataService alertDataService;

    /**
     * 封装并保存报警数据
     * @param deviceData
     * @param alertRule
     * @param ids
     */
    private List<AlertData> insertAlertData(DeviceData deviceData, AlertRule alertRule, Collection<Long> ids) {
        //属性拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        //状态，报警原因、报警类型
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setAlertRuleId(alertRule.getId());
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);

        List<AlertData> list = ids.stream().map(userId -> {
            //属性拷贝
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            dbAlertData.setCreateTime(null);
            return dbAlertData;

        }).collect(Collectors.toList());

        //批量保存
        alertDataService.saveBatch(list);

        return list;

    }

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule)?1:0;
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule)?1:0;
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id)?1:0;
    }

}
